import { useEffect, useState } from "react";
import axios from "../../axios";
import { Button, Table, Modal, Input, Row, Col, Tag ,message} from 'antd';
import {CloseCircleOutlined} from "@ant-design/icons"
function GoodsSpecs() {

    const [list, setList] = useState([])
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const [limit, setLimit] = useState(10)
    const getList = async () => {
        let { list, total } = await axios.get("/store/product/rule/list", {
            params: {
                page,
                limit,
                keywords: "",
                temp: new Date().getTime(),
            }
        })
        setList(list)
        setTotal(total)
    }
    const onchangeFun = (a, b) => {
        console.log(a, b);
        setPage(a);
        setLimit(b)

    }
    useEffect(() => {
        getList()
    }, [page, limit])
    const columns = [ // 表格列名******
        {
            title: 'ID',
            dataIndex: 'id',
            key: "id"
        },
        {
            title: '规格名称',
            dataIndex: 'ruleName',
            key: "ruleName"
        },
        {
            title: '商品规格',
            dataIndex: 'ruleValue',
            key: "ruleValue",
            render: (_, row) => {
                return (<>

                    {
                        JSON.parse(row.ruleValue).map(item => <div key={item.value}>{item.value}</div>)
                    }
                </>)

            }
        },
        {
            title: '商品属性',
            dataIndex: 'ruleValue',
            key: "ruleValue",
            render: (_, row) => {
                return (<>

                    {
                        JSON.parse(row.ruleValue).map(item => <div key={item.value}>{item.detail.join(",")}</div>)
                    }
                </>)

            }
        },
        {
            title: "操作",
            dataIndex: "X",
            key: "X",
            render: (_, row) => <Button onClick={() => editorBtn(row)}>编辑</Button>
        }
    ];
    const [isModalOpen, setIsModalOpen] = useState(false);//模态框显示和隐藏
    const [title, setTitle] = useState("增加");
    const [rowId, setrowid] = useState(0)
    const addBtn = () => { setIsModalOpen(true); setTitle("增加"); setrowid(0) }//增加按钮
    const editorBtn = (row) => { 
        setIsModalOpen(true); setTitle("编辑");
        setNames(row.ruleName)
        setrowid(row.id)
        setruleValue(JSON.parse(row.ruleValue))
     }// 编辑按钮
    const handleCancel = () => { setIsModalOpen(false); setNames("") };//模态框关闭事件
    const [names, setNames] = useState("")
    const saveAxios = async (url) => {
        let res = await axios.post(url, {
            id: rowId,
            ruleName: names,
            ruleValue: JSON.stringify(ruleValue),

        })
    }
    const submitFun = () => {//确定

        if(names==""){
            message.open({
                type: 'error',
                content: '请输入规格名称',
              });
            return false
         }
        if (title == "增加") {
            console.log(names, ruleValue);
            saveAxios("/store/product/rule/save")
        } else {//编辑
            saveAxios("/store/product/rule/update")
        }
        setNames("")
        setIsModalOpen(false);
        getList()
    }
    const [showBtn, setshwobtn] = useState(true)
    const addNewRules = () => {
        setshwobtn(false)
    }
    const [inputValue, setinputValue] = useState("")//商品规格
    const [inputDetail, setinputDetail] = useState("")//商品规格值
    const [ruleValue, setruleValue] = useState([])
    const yesAddrules = () => {//  单机确定时候 push{}


        if(inputValue==""||inputDetail==""){
            message.open({
                type: 'error',
                content: '请输入规格名称或规格值',
              });
            return false
         }
        let obj = { value: inputValue, detail: [inputDetail], inputVisible: false }
        console.log(obj);

        setruleValue(pre => {
            pre.push(obj)
            return [...pre]
        })
        getList()
        setinputValue("")
        setinputDetail("")
        setshwobtn(true)
    }

    const addItem = (index) => {
        setruleValue(pre => {
            pre[index].inputVisible = true;
            return [...pre]
        })
    }

    const onBlurFun = (e, index) => {
        
        if(e.target.value==""){
            message.open({
                type: 'error',
                content: '请输入规格名称或规格值',
              });
            return false
         }
        setruleValue(pre => {
            pre[index].inputVisible = false;
            pre[index].detail.push(e.target.value)
            return [...pre]
        })
    }
    const removeObj = (index) => {
        setruleValue(pre => {
            pre.splice(index, 1)
            return [...pre]
        })
    }
    const delFun = (index, i) => {
        setruleValue(pre => {
            pre[index].detail.splice(i, 1)
            return [...pre]
        })
    }
    return (
        <div className="whitebg">
        <Button danger onClick={addBtn}>增加</Button>
        <Table columns={columns} rowKey="id" dataSource={list} pagination={{
            total,
            pageSize: limit,
            showQuickJumper: true,
            onChange: onchangeFun
        }} />

        <Modal title={title} open={isModalOpen} footer={null} onCancel={handleCancel}>
            <Input value={names} onChange={(e) => setNames(e.target.value)}></Input>

            {

                ruleValue.map((item, index) => {
                    return (<div key={index}>
                        <Tag color="#f50" >
                            {item.value}
                            <CloseCircleOutlined onClick={() => removeObj(index)}/>
                        </Tag>

                        <section>
                            {
                                item.detail.map((items, i) => {
                                    return (<Tag color="#108ee9" key={i}>{items}  <CloseCircleOutlined onClick={() => delFun(index, i)}/></Tag>)
                                })
                            }

                            {
                                item.inputVisible ? <Input onBlur={(e) => onBlurFun(e, index)} style={{ width: "50px" }} type="text" /> : <Button onClick={() => addItem(index)}>+增加</Button>
                            }


                        </section>

                    </div>)
                })
            }






            {
                showBtn ? <Button type="primary" onClick={addNewRules}>添加新规格</Button> : <Row gutter="16">
                    <Col span={8}>
                        <Input value={inputValue} onChange={(e) => setinputValue(e.target.value)} placeholder="输入规格"></Input>
                    </Col>
                    <Col span={8}>
                        <Input value={inputDetail} onChange={(e) => setinputDetail(e.target.value)} placeholder="输入规格值"></Input>
                    </Col>
                    <Col span={8}>
                        <Button onClick={() => yesAddrules()}>确定</Button>
                        <Button onClick={() => setshwobtn(true)}>取消</Button>
                    </Col>
                </Row>
            }

            <div className="center">
                <Button onClick={submitFun} type="primary">确定</Button>

            </div>
        </Modal>
    </div>

    );
}

export default GoodsSpecs;